package problem442;

import java.util.ArrayList;
import java.util.List;

//442.数组中的重复数据
//https://leetcode.cn/problems/find-all-duplicates-in-an-array/

class Solution {
    public List<Integer> findDuplicates(int[] nums) {
        int n = nums.length;
        List<Integer> list = new ArrayList<>();
        for(int i = 0; i<n; i++) {
            while(nums[i] != nums[nums[i] - 1]) {
                swap(nums, i, nums[i]-1);
            }
        }
        // System.out.println(Arrays.toString(nums));
        for(int i = 0; i<n; i++) {
            if(nums[i] - 1 != i) list.add(nums[i]);
        }
        return list;
    }

    private void swap(int[] nums, int a, int b) {
        int t = nums[a];
        nums[a] = nums[b];
        nums[b] = t;
    }
}

/*

4 3 2 7 8 2 3 1

0 1 2 3 4 5 6 7
1 2 3 4 8 2 7 8

*/